{
 "cells": [
  {
   "cell_type": "raw",
   "id": "0e77c293-4049-43be-ba49-ff9daeefeee7",
   "metadata": {},
   "source": [
    "---\n",
    "sidebar_position: 4\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14d3fd06",
   "metadata": {},
   "source": [
    "# Per-User Retrieval\n",
    "\n",
    "When building a retrieval app, you often have to build it with multiple users in mind. This means that you may be storing data not just for one user, but for many different users, and they should not be able to see eachother's data. This means that you need to be able to configure your retrieval chain to only retrieve certain information. This generally involves two steps.\n",
    "\n",
    "**Step 1: Make sure the retriever you are using supports multiple users**\n",
    "\n",
    "At the moment, there is no unified flag or filter for this in LangChain. Rather, each vectorstore and retriever may have their own, and may be called different things (namespaces, multi-tenancy, etc). For vectorstores, this is generally exposed as a keyword argument that is passed in during `similaritySearch`. By reading the documentation or source code, figure out whether the retriever you are using supports multiple users, and, if so, how to use it.\n",
    "\n",
    "Note: adding documentation and/or support for multiple users for retrievers that do not support it (or document it) is a GREAT way to contribute to LangChain\n",
    "\n",
    "**Step 2: Add that parameter as a configurable field for the chain**\n",
    "\n",
    "The LangChain `config` object is passed through to every Runnable. Here you can add any fields you'd like to the `configurable` object. Later, inside the chain we can extract these fields.\n",
    "\n",
    "**Step 3: Call the chain with that configurable field**\n",
    "\n",
    "Now, at runtime you can call this chain with configurable field.\n",
    "\n",
    "## Code Example\n",
    "\n",
    "Let's see a concrete example of what this looks like in code. We will use Pinecone for this example."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8ccbef7",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "### Install dependencies\n",
    "\n",
    "```{=mdx}\n",
    "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
    "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
    "\n",
    "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
    "\n",
    "<Npm2Yarn>\n",
    "  @langchain/pinecone @langchain/openai @pinecone-database/pinecone @langchain/core\n",
    "</Npm2Yarn>\n",
    "```\n",
    "\n",
    "### Set environment variables\n",
    "\n",
    "We'll use OpenAI and Pinecone in this example:\n",
    "\n",
    "```env\n",
    "OPENAI_API_KEY=your-api-key\n",
    "\n",
    "PINECONE_API_KEY=your-api-key\n",
    "PINECONE_INDEX=your-index-name\n",
    "\n",
    "# Optional, use LangSmith for best-in-class observability\n",
    "LANGSMITH_API_KEY=your-api-key\n",
    "LANGCHAIN_TRACING_V2=true\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "75823b2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import { OpenAIEmbeddings } from \"@langchain/openai\";\n",
    "import { PineconeStore } from \"@langchain/pinecone\";\n",
    "import { Pinecone } from \"@pinecone-database/pinecone\";\n",
    "import { Document } from \"@langchain/core/documents\";"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7345de3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "const embeddings = new OpenAIEmbeddings()\n",
    "\n",
    "const pinecone = new Pinecone();\n",
    "\n",
    "const pineconeIndex = pinecone.Index(Deno.env.get(\"PINECONE_INDEX\"));\n",
    "\n",
    "const vectorStore = await PineconeStore.fromExistingIndex(\n",
    "  new OpenAIEmbeddings(),\n",
    "  { pineconeIndex }\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3436f41e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ \u001b[32m\"39d90a6d-7e97-45cc-a9dc-ebefa47220fc\"\u001b[39m ]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await vectorStore.addDocuments(\n",
    "  [new Document({ pageContent: \"i worked at kensho\" })],\n",
    "  { namespace: \"harrison\" }\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7d808279",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ \u001b[32m\"75f94962-9135-4385-b71c-36d8345e02aa\"\u001b[39m ]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await vectorStore.addDocuments(\n",
    "  [new Document({ pageContent: \"i worked at facebook\" })],\n",
    "  { namespace: \"ankush\" }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39c11920",
   "metadata": {},
   "source": [
    "The pinecone kwarg for `namespace` can be used to separate documents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3c2a39fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ Document { pageContent: \u001b[32m\"i worked at facebook\"\u001b[39m, metadata: {} } ]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// This will only get documents for Ankush\n",
    "await vectorStore.asRetriever({\n",
    "    filter: {\n",
    "        namespace: \"ankush\",\n",
    "    }\n",
    "}).getRelevantDocuments(\n",
    "    \"where did i work?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "56393baa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ Document { pageContent: \u001b[32m\"i worked at kensho\"\u001b[39m, metadata: {} } ]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// This will only get documents for Harrison\n",
    "await vectorStore.asRetriever({\n",
    "    filter: {\n",
    "        namespace: \"harrison\",\n",
    "    }\n",
    "}).getRelevantDocuments(\n",
    "    \"where did i work?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88ae97ed",
   "metadata": {},
   "source": [
    "We can now create the chain that we will use to do question-answering over"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "62707b4f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import { StringOutputParser } from \"@langchain/core/output_parsers\";\n",
    "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
    "import {\n",
    "    RunnableBinding,\n",
    "    RunnableLambda,\n",
    "    RunnablePassthrough,\n",
    "} from \"@langchain/core/runnables\";\n",
    "import { ChatOpenAI, OpenAIEmbeddings } from \"@langchain/openai\";"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6778ffa",
   "metadata": {},
   "source": [
    "This is basic question-answering chain set up."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "44a865f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "const template = `Answer the question based only on the following context:\n",
    "{context}\n",
    "Question: {question}`\n",
    "\n",
    "const prompt = ChatPromptTemplate.fromTemplate(template)\n",
    "\n",
    "const model = new ChatOpenAI({\n",
    "  modelName: \"gpt-3.5-turbo-0125\",\n",
    "  temperature: 0,\n",
    "})\n",
    "\n",
    "const retriever = vectorStore.asRetriever()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d481b70",
   "metadata": {},
   "source": [
    "We can now create the chain using our configurable retriever. It is configurable because we can define any object which will be passed to the chain. From there, we extract the configurable object and pass it to the vectorstore."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "210b0446",
   "metadata": {},
   "outputs": [],
   "source": [
    "import { RunnableSequence } from \"@langchain/core/runnables\"\n",
    "\n",
    "const chain = RunnableSequence.from([\n",
    "    {\n",
    "        context: async (input, config) => {\n",
    "            if (!config || !(\"configurable\" in config)) {\n",
    "                throw new Error(\"No config\")\n",
    "            }\n",
    "            const { configurable } = config;\n",
    "            return JSON.stringify(await vectorStore.asRetriever(configurable).getRelevantDocuments(input));\n",
    "        },\n",
    "        question: new RunnablePassthrough(),\n",
    "    },\n",
    "    prompt,\n",
    "    model,\n",
    "    new StringOutputParser(),\n",
    "])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f6458c3",
   "metadata": {},
   "source": [
    "We can now invoke the chain with configurable options. `search_kwargs` is the id of the configurable field. The value is the search kwargs to use for Pinecone"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "a38037b2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32m\"The user worked at Kensho.\"\u001b[39m"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await chain.invoke(\n",
    "    \"where did the user work?\",\n",
    "    { configurable: { filter: { namespace: \"harrison\" }}},\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "0ff4f5f2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32m\"The user worked at Facebook.\"\u001b[39m"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await chain.invoke(\n",
    "    \"where did the user work?\",\n",
    "    { configurable: { filter: { namespace: \"ankush\" }}},\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fb27b941602401d91542211134fc71a",
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "For more vectorstore implementations for multi-user, please refer to specific pages, such as [Milvus](/docs/integrations/vectorstores/milvus)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Deno",
   "language": "typescript",
   "name": "deno"
  },
  "language_info": {
   "file_extension": ".ts",
   "mimetype": "text/x.typescript",
   "name": "typescript",
   "nb_converter": "script",
   "pygments_lexer": "typescript",
   "version": "5.3.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
